package data

import (
	"encoding/json"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/wire"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sgw-services/app/rate/service/internal/conf"
	"time"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewRateRepo)

// Data .
type Data struct {
	// TODO wrapped database client
	db *gorm.DB
	// TODO wrapped redis client
}

// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
	cleanup := func() {
		log.NewHelper(logger).Info("closing the data resources")
	}
	dialector := mysql.Open(c.Database.Source)

	db, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		panic(fmt.Errorf("gorm open db err info : %s", err))
	}
	sqlDb, err := db.DB()
	if err != nil {
		panic(fmt.Sprintf("has some error sqlDb, err := db.DB(); err:%s", err))
	}
	//配置连接池
	sqlDb.SetMaxIdleConns(int(c.Database.MaxIdleConns))
	sqlDb.SetMaxOpenConns(int(c.Database.MaxOpenConns))
	sqlDb.SetConnMaxLifetime(time.Duration(c.Database.ConnMaxLifetime) * time.Minute)

	result, _ := json.Marshal(sqlDb.Stats())
	log.NewHelper(logger).Info(string(result))

	return &Data{db: db}, cleanup, nil
}
